package com.wlyuan.open.scanner.domain.message;

import com.alibaba.fastjson.JSON;
import lombok.var;
import org.apache.commons.lang3.tuple.Pair;

import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author lijing
 * @description
 */
public class MessageTableParse {

    /**
     * 获取表名
     *
     * @param source
     * @return
     */
    public static String getTableName(String source) {
        var map = getTableInfo(source);
        return Optional.ofNullable(map)
                .map(m -> String.valueOf(m.get(FilterFieldEnum.table.name())))
                .orElse(null);
    }

    /**
     * 获取操作表信息
     *
     * @param source
     * @return
     */
    private static Map<String, Object> getTableInfo(String source) {
        return Optional.ofNullable(source).map(d -> {
            Map<String, Object> sourceMap = JSON.parseObject(d, Map.class);
            return Optional.ofNullable(sourceMap).map(MessageTableParse::mapFilter).orElse(null);
        }).orElse(null);
    }

    private static Map<String, Object> mapFilter(Map<String, Object> map) {
        return map.entrySet().stream()
                .map(Map.Entry::getKey)
                .filter(fieldName -> map.get(fieldName) != null && FilterFieldEnum.filterJsonField(fieldName))
                .map(fieldName -> Pair.of(fieldName, map.get(fieldName)))
                .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    }

}
